// pages/search/search.js
import axios from "../../utils/axios";
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    store_id: null,
    search: '', //搜索文本框
    goods: [], //搜索到的商品信息
    defaultImage: 'https://image.petintech.com/images/pet-logo.jpg', //默认图片
    reachBottom: [], //如果上啦刷新没有数据的话 就不请求接口
    page: 1, //页码
    attachList: [], //点击规格弹框渲染
    attachFlag: true, //是否隐藏模态框
    attachType: 'goods', //打开模态框是什么类型 服务还是商城
    showpic: '', //淡出 懒加载
    hidepic: '', //淡入
    goodsInfo: null,
    shopp: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let store_id = options.store_id ? options.store_id : null,
      search = options.search ? options.search : '';
    this.setData({
      search: search,
      store_id: store_id,
    });
    this.goods();
  },

  // 选择规格数量
  selectAttachCount: function (e) {

    let goodsId = e.currentTarget.dataset.goodsid

    console.log(goodsId)

    let list = this.data.goods

    for (let i = 0; i < list.length; i++) {

      if (list[i].goods_id == goodsId) {
        // 无规格，则给一个通用
        if (list[i].attach == undefined || list[i].attach.length <= 0) {
          let param = [{
            attach_id: '-1',
            name: '通用',
            discount: 0,
            price: list[i].discount > 0.01 ? list[i].discount : list[i].price,
            stock: list[i].stock
          }]
          list[i]['attach'] = param
          this.setData({
            goodsInfo: list[i],
            shopp: true
          })
        } else {
          this.setData({
            goodsInfo: list[i],
            shopp: true
          })
        }
      }

    }


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
    })
    this.goods();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1500)
  },
  /**
   * 返回顶部事件
   */
  backTop: function () {
    console.log("触发返回顶部")
    this.setData({
      page: 1,
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      page: this.data.page + 1,
    });
    if (this.data.reachBottom.length > 0) {
      this.goods();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  /**
   * 搜索
   */
  search(e) {
    let val = e.detail.value;
    if (val == '') {
      return
    }
    this.setData({
      search: val,
      page: 1
    })
    this.goods();
  },
  goods() {
    wx.showLoading({
      title: '加载中...',
      mask: true,
    });
    const self = this;

    axios('/groupon/searchGoods', {
      content: self.data.search,
      page: self.data.page
    }).then(res => {
      wx.hideLoading();
      let data = res.data,
        code = data.resultcode,
        result = data.result;
      if (code == 1) {
        let i, len = result.length;
        for (i = 0; i < len; i++) {
          result[i].lazyIndex = null;
        };
        if (self.data.page == 1) {
          self.setData({
            reachBottom: result,
            goods: app.disposeList(result)
          });
        } else {
          self.setData({
            reachBottom: result,
            goods: app.disposeList(self.data.goods.concat(result))
          });
        }

      }
    })

  },
  /**
   * 加入购物车 无规格 添加商品
   */
  plusGoods(e) {
    const self = this;
    let goods_id = e.currentTarget.dataset.goods_id;
    api.request({
      url: '/store/optGoods',
      data: {
        goods_id: goods_id,
      },
      success(res) {
        let data = res.data,
          code = data.resultcode,
          result = data.result;
        if (code == 1) {
          wx.showToast({
            title: '添加成功!',
          });
        }
      }
    })
  },
  /**
   * 跳转详情页面
   */
  details(e) {
    let goods_id = e.currentTarget.dataset.goods_id,
      store_id = this.data.store_id == 'null' || this.data.store_id ? 33 : this.data.store_id;
    wx.navigateTo({
      url: `/pages/mallDetails/mallDetails?g_id=${goods_id}&s_id=${store_id}`
    })
  },
  /**
   * 打开规格模态框
   */
  openModal(e) {
    let goods_id = e.currentTarget.dataset.goods_id,
      i, goods = this.data.goods,
      len = goods.length;
    for (i = 0; i < len; i++) {
      if (goods_id == goods[i].goods_id) {
        this.setData({
          attachList: goods[i],
          attachFlag: false,
        });
        return
      }
    }
  },
  /**
   * 规格 加入购物车
   */
  tocart(e) {
    console.log(e);
    let data = e.detail,
      goods_id = data.goodsId,
      stock = data.stock,
      count = data.count,
      attach_id = data.attachId;
    api.request({
      url: '/store/optGoods',
      data: {
        goods_id: goods_id,
        attach_id: attach_id,
        num: count
      },
      success(res) {
        let data = res.data,
          code = data.resultcode,
          result = data.result;
        if (code == 1) {
          wx.showToast({
            title: '添加成功!',
          });
        } else {
          wx.switchTab({
            url: '/pages/personal/personal',
          })
        }

      }
    })
  },
  /**
   * 返回上一页
   */
  back() {
    wx.navigateBack({
      detail: 1
    })
  },
  /**
   * 图片初始化
   */
  imgLoad(id, src, index) {
    const self = this;
    // 查询每张图片在页面当中的位置 使图片懒加载 瀑布流
    let i, goodsLen = self.data.goods.length,
      goods = self.data.goods,
      timer = null,
      animation = wx.createAnimation({}); //创建一个动画实例
    for (i = 0; i < goodsLen; i++) {
      //显示图片
      let gid = parseInt(goods[i].goods_id),
        menuIndexStr = 'goods[' + i + '].lazyIndex';
      if (gid == id) {
        if (timer) clearTimeout(timer);
        //淡入
        animation.opacity(1).step({
          duration: 800
        });

        //描述动画
        self.setData({
          showpic: animation.export(),
        });
        //淡出
        animation.opacity(0).step({
          duration: 800
        });
        //描述动画
        self.setData({
          hidepic: animation.export(),
        });
        timer = setTimeout(() => {
          self.setData({
            [menuIndexStr]: index
          });
        }, 800)
      }
    }
  },
  //图片懒加载 
  lazyload(e) {
    const self = this;
    let data = e.currentTarget.dataset,
      id = data.goods_id,
      src = data.src,
      index = data.index;
    self.imgLoad(id, src, index);
  },
})